import asyncio
import json
import websockets

async def connect_to_server(ip='localhost', port=10086):
    """连接到WebSocket服务器"""
    uri = f"ws://{ip}:{port}/ws"
    print(f"尝试连接到: {uri}")
    try:
        websocket = await websockets.connect(uri)
        print("连接成功！")
        return websocket
    except Exception as e:
        print(f"连接失败: {e}")
        return None

async def send_message(websocket, message):
    """通过WebSocket发送消息"""
    if websocket:
        try:
            await websocket.send(json.dumps(message))
            print(f"已发送消息: {message}")
        except Exception as e:
            print(f"发送消息时出错: {e}")

async def receive_message(websocket):
    """接收WebSocket消息"""
    if websocket:
        try:
            response = await websocket.recv()
            print(f"收到消息: {response}")
            return json.loads(response)
        except Exception as e:
            print(f"接收消息时出错: {e}")
            return None

async def disconnect(websocket):
    """断开与WebSocket服务器的连接"""
    if websocket:
        try:
            await websocket.close()
            print("已断开连接")
        except Exception as e:
            print(f"断开连接时出错: {e}")

async def main():
    # 示例使用步骤
    websocket = await connect_to_server()
    if websocket:
        await send_message(websocket, {"cmd": "register"})
        response = await receive_message(websocket)
        print("服务器响应:", response)
        await disconnect(websocket)

if __name__ == "__main__":
    asyncio.run(main())